<template>
  <div class="mar-auto" style="width: 800px">
    <div v-if="!hasSubmitCanvas">
      <div class="clear-float">
        <el-button @click="showDialog()" class="pull-left" type="primary">添加 Label</el-button>
        <el-button @click="deleteLabel()" class="pull-left" type="danger">删除 Label</el-button>
        <el-button @click="submitCanvas()" class="pull-right" type="success">提交画布</el-button>
      </div>
      <br/>
      <div id="addCanvas">
        <canvas id="canvas-todo" width="800px" height="500px" style="border: 1px solid #888;"></canvas>
      </div>
      <br/>

      <img src="../assets/logo.png" id="my-image" style="display: none">

      <el-dialog title="添加 Label" :visible.sync="dialogVisible" size="tiny">
        <img src="../assets/demo.jpg" width="246" style="margin-bottom: 10px">
        <el-form ref="createCanvas" :model="createCanvas" label-width="100px" label-position="right">
          <el-form-item label="产品名称:">
            <el-input v-model="createCanvas.title"></el-input>
          </el-form-item>
          <el-form-item label="产品ID:">
            <el-input v-model="createCanvas.productID"></el-input>
          </el-form-item>
          <el-form-item label="产品数量:">
            <el-input v-model="createCanvas.productAmount"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addCanvas()" class="pull-right">立即创建</el-button>
            <el-button class="pull-right mar-right-10" @click="resetForm()">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>

    <div v-show="hasSubmitCanvas">
      <canvas id="showCanvas" width="800px" height="500px" style="border: 1px solid #888;"></canvas>
    </div>
  </div>
</template>

<script>
  import 'fabric'
  export default {
    data () {
      return {
        canvas: null,
        dialogVisible: false,
        canvasGroup: [],
        curGroup: null,
        hasSubmitCanvas: false,
        createCanvas: {
          title: '-产品名称-',
          productID: '-产品ID-',
          productAmount: '-产品数量-'
        }
      }
    },
    mounted () {
      this.createFabric()
    },
    methods: {
      DrawGrid () {
        let CANVAS_WIDTH = 800;
        let CANVAS_HEIGHT = 500;
        let GRID_length = 25;
        let CELL_length = 50;

        let cols = parseInt(CANVAS_WIDTH / GRID_length);
        let rows = parseInt(CANVAS_HEIGHT / GRID_length);
        // 绘制纵轴
        for (let i = 0; i < cols; i++) {
          // 绘制横坐标
          if (i === 0) {
            let Ypath = new fabric.Line([ 0, 0, 0, CANVAS_HEIGHT ], {
              stroke: '#2898E0',
              strokeWidth: 2,
              selectable: false
            });
            this.canvas.add(Ypath);
            for (let k = 0; k < rows; k++) {
              let axis = k * CELL_length + "";
              let text = new fabric.Text(axis, {
                fontSize: 14, left: k * CELL_length, top: 5, fill: '#333', fontFamily: 'Comic Sans', fontWeight: 'normal',
                selectable: false
              });
              this.canvas.add(text)
            }
            continue
          }
          let Ypath = new fabric.Line([ i * GRID_length, 0, i * GRID_length, CANVAS_HEIGHT ], {
            stroke: '#888',
            strokeWidth: 0.25,
            selectable: false
          });
          this.canvas.add(Ypath);
        }
        // 绘制横轴
        for (let j = 0; j < rows; j++) {
          // 绘制纵坐标
          if (j === 0) {
            let Xpath = new fabric.Line([ 0, 0, CANVAS_WIDTH, 0 ], {
              stroke: '#2898E0',
              strokeWidth: 2,
              selectable: false
            });
            this.canvas.add(Xpath);
            for (let k = 0; k < cols; k++) {
              let axis = k * CELL_length + "";
              let text = new fabric.Text(axis, {
                fontSize: 14, left: 0, top: k * CELL_length + 5, fill: '#333', fontFamily: 'Comic Sans', fontWeight: 'normal',
                selectable: false
              });
              this.canvas.add(text)
            }
            continue
          }
          let Xpath = new fabric.Line([ 0, j * GRID_length, CANVAS_WIDTH, j * GRID_length ], {
            stroke: '#888',
            strokeWidth: 0.25,
            selectable: false
          });
          this.canvas.add(Xpath);
        }
      },
      createFabric () {
        // create a wrapper around native canvas element (with id="canvas-todo")
        this.canvas = new fabric.Canvas('canvas-todo');
        this.canvas.set({backgroundColor: '#ffd'});

        this.DrawGrid();
        // this.initData();
        this.createLabel();

//        canvas.on('mouse:down', function(options) {
//          console.log(canvas.getObjects());
//        });
//        rect.on('modified', function() {
//          console.log('selected a rectangle');
//          console.log(rect.getWidth());
//          console.log(rect.getHeight());
//        });
//        circle.on('selected', function() {
//          console.log('selected a circle');
//        });

//        console.log(canvas.item(0))
//        console.log(this.canvas.getObjects())
//
//        let allItems = canvas.getObjects()
//        allItems.forEach((item) => {
//          item.selectable = false
//          console.log(item.text)
//        })
      },
      initData () {
        let circle = new fabric.Circle({});
        let triangle = new fabric.Triangle({
          width: 50, height: 50, left: 50, top: 50, fill: 'blue'
        });
        circle.set({radius: 20, left: 150, top: 150, fill: 'orange'});
        this.canvas.add(circle, triangle);

        // create a image
        let imgElement = document.getElementById('my-image');
        let imgInstance = new fabric.Image(imgElement, {
          left: 250,
          top: 50,
          angle: 0,
          opacity: 0.85
        });
        this.canvas.add(imgInstance);

        let buttonRect = new fabric.Rect({
          width: 45, height: 30, fill: '#FF4949', originX: 'center', originY: 'center'
        });
        let buttonText = new fabric.Text('删 除', {
          fontSize: 13, fill: 'white', fontFamily: 'Comic Sans', fontWeight: 'normal', originX: 'center', originY: 'center'
        });
        let button = new fabric.Group([ buttonRect, buttonText ], {
          left: 195, top: -30, hasControls: false, selectable: true, visible: false
        });

        // create a group
        let rect = new fabric.Rect({
          width: 180, height: 80, fill: 'red', originX: 'center', originY: 'center'
        });
        let text = new fabric.Text('Hello World', {
          fontSize: 30, originX: 'center', originY: 'center', fill: 'yellow', fontFamily: 'Comic Sans', fontWeight: 'normal'
        });
        let group = new fabric.Group([ rect, text ], {
          left: 100, top: 250, angle: 15
        });
        this.canvas.add(group);
      },
      createLabel () {
        function createText(text, fontSize, X, Y ) {
          return new fabric.Text(text, {
            fontSize: fontSize, fill: '#000', fontFamily: 'Comic Sans', fontWeight: 'normal', left: X, top: Y
          });
        }

        let rect = new fabric.Rect({
          width: 240, height: 120, fill: 'white', originX: 'left', originY: 'top', stroke: '#eee', strokeWidth: 2,
        });
        let path = new fabric.Line([ 0, 45, 240, 45 ], {
          stroke: '#eee',
          strokeWidth: 1,
          selectable: false
        });
        let title = createText(this.createCanvas.title, 16, 15, 15);

        let productText_ID = createText('Product ID :', 14, 15, 60);
        let productID = createText(this.createCanvas.productID, 14, 110, 60);

        let productText_Amount = createText('Product Amount :', 14, 15, 85);
        let productAmount = createText(this.createCanvas.productAmount.toString(), 14, 150, 85);

        let group = new fabric.Group([ rect, title, path, productText_ID, productID, productText_Amount, productAmount ], {
          left: 500, top: 350, hasControls: false,
          productID: this.createCanvas.productID,
          title: this.createCanvas.title
        });
        this.canvasGroup.push(group);
        this.canvas.add(group);

        group.on('selected', function() {
          // console.log(group.title);
          this.curGroup = group
        }.bind(this));
      },
      showDialog () {
        this.resetForm();
        this.dialogVisible = true;
      },
      addCanvas () {
        // console.log(this.createCanvas)
        // todo: 判空、判重
        let isRepeated = this.canvasGroup.some((data) => {
          return data.productID === this.createCanvas.productID
        });
        if (isRepeated) {
          this.$message.error('产品ID已存在');
          return
        }

        this.createLabel();
        this.resetForm()
      },
      resetForm() {
        this.dialogVisible = false;
        this.createCanvas = {
          title: '',
          productID: '',
          productAmount: ''
        }
      },
      submitCanvas () {
        // console.log(this.canvasGroup)
        if (!this.canvasGroup.length) {
          this.$message.error('至少创建一个Label');
          return
        }
        let canvas = new fabric.Canvas('showCanvas');
        canvas.set({backgroundColor: '#f1f1f1'});
        this.canvasGroup.forEach((group) => {
          group.selectable = false;
          canvas.add(group)
        });
        this.hasSubmitCanvas = true
      },
      deleteLabel () {
        // console.log(this.curGroup)
        if (!this.curGroup) {
          this.$message({
            type: 'info',
            message: '未选择具体 Label'
          });
          return
        }
        this.$confirm(`确定删除产品：${this.curGroup.title} ？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.canvas.remove(this.curGroup);
          this.canvasGroup.forEach((group, index) => {
            if (group.productID === this.curGroup.productID) {
              this.canvasGroup.splice(index, 1)
            }
          });
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.curGroup = null
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>
